<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html>
<head>
<script src="../../resources/testharness.js"></script>
<script src="../../resources/testharnessreport.js"></script>
<script src="../../resources/gc.js"></script>
</head>
<body>
<script>

// Check that the number of peerconnections we can create hasn't regressed.
// At the moment (Nov 2017), the limit is approx
// - 770 on Mac
// - 850 on Windows
// - 1700 on Linux

let peerConnections = [];

function allocatePeerConnection() {
  peerConnections.push(new RTCPeerConnection());
}

async function cleanUpPeerConnectionsAndGarbageCollect() {
  // Close all peer connections so that they may be garbage collected.
  peerConnections.forEach(pc => {
    pc.close();
  });
  peerConnections = [];
  await asyncGC();
}

promise_test(async function() {
  try {
    // These many peer connections should be OK to allocate.
    while (internals.peerConnectionCount() <
           internals.peerConnectionCountLimit) {
      allocatePeerConnection();
    }
    // Exceeding the limit should throw an UnknownError.
    assert_throws_dom("UnknownError", allocatePeerConnection,
                      'Creating too many RTCPeerConnections gives UnknownError');
  } finally {
    // On swarming bots running blink_web_tests (such as win7-rel), garbage
    // collection is not guaranteed to occur between test pages. As such we
    // cannot assume that the initial count is 0, and we must clean up after
    // this test regardless of test result or unrelated tests may fail.
    let totalAllocatedPeerConnections = internals.peerConnectionCount();
    let peerConnectionsAllocatedByTest = peerConnections.length;
    await cleanUpPeerConnectionsAndGarbageCollect();
    // We cannot assert there are no peer connections since other swarming tests
    // could have left peer connections in a non-closed state, but we can assert
    // that at least all |peerConnectionsAllocatedByTest| have been collected.
    assert_less_than_equal(
      internals.peerConnectionCount(),
      totalAllocatedPeerConnections - peerConnectionsAllocatedByTest);
  }
}, 'Create and garbage collect many RTCPeerConnections');

</script>
</body>
</html>
